package com.yougou.utils;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yougou.data.model.User;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

public class UserDataManager {
    
    private static final String KEY_USERS = "key_registered_users";
    private static Gson gson = new Gson();
    
    
    public static boolean registerUser(String username, String phone, String password) {
        Map<String, UserInfo> users = getUsers();
        
        // 检查用户名是否已存在
        if (users.containsKey(username)) {
            return false;
        }
        
        // 检查手机号是否已存在
        for (UserInfo info : users.values()) {
            if (info.phone.equals(phone)) {
                return false;
            }
        }
        
        // 创建用户信息
        UserInfo userInfo = new UserInfo();
        userInfo.username = username;
        userInfo.phone = phone;
        userInfo.password = password;
        userInfo.uid = "UID_" + System.currentTimeMillis();
        
        users.put(username, userInfo);
        saveUsers(users);
        
        return true;
    }
    
    
    public static boolean isUsernameTaken(String username, String currentUid) {
        Map<String, UserInfo> users = getUsers();
        
        for (UserInfo info : users.values()) {
            // 排除当前用户自己
            if (!info.uid.equals(currentUid) && info.username.equals(username)) {
                return true;
            }
        }
        
        return false;
    }
    
    
    public static boolean isPhoneTaken(String phone, String currentUid) {
        Map<String, UserInfo> users = getUsers();
        
        for (UserInfo info : users.values()) {
            // 排除当前用户自己
            if (!info.uid.equals(currentUid) && info.phone.equals(phone)) {
                return true;
            }
        }
        
        return false;
    }
    
    
    public static boolean updateUserInfo(String uid, String newUsername, String newPhone) {
        Map<String, UserInfo> users = getUsers();
        
        // 查找要更新的用户
        UserInfo targetUser = null;
        String oldUsername = null;
        
        for (Map.Entry<String, UserInfo> entry : users.entrySet()) {
            if (entry.getValue().uid.equals(uid)) {
                targetUser = entry.getValue();
                oldUsername = entry.getKey();
                break;
            }
        }
        
        if (targetUser == null) {
            return false;
        }
        
        // 如果用户名改变了，需要更新Map的key
        if (!oldUsername.equals(newUsername)) {
            users.remove(oldUsername);
            targetUser.username = newUsername;
            users.put(newUsername, targetUser);
        }
        
        // 更新手机号
        targetUser.phone = newPhone;
        
        saveUsers(users);
        return true;
    }
    
    
    public static boolean changePassword(String uid, String oldPassword, String newPassword) {
        Map<String, UserInfo> users = getUsers();
        
        // 查找用户
        for (UserInfo info : users.values()) {
            if (info.uid.equals(uid)) {
                // 验证旧密码
                if (!info.password.equals(oldPassword)) {
                    return false;
                }
                
                // 更新密码
                info.password = newPassword;
                saveUsers(users);
                return true;
            }
        }
        
        return false;
    }
    
    
    public static User validateLogin(String username, String password) {
        Map<String, UserInfo> users = getUsers();
        
        UserInfo userInfo = users.get(username);
        if (userInfo == null) {
            return null; // 用户不存在
        }
        
        if (!userInfo.password.equals(password)) {
            return null; // 密码错误
        }
        
        // 登录成功，返回用户对象（包含完整信息）
        User user = new User();
        user.setUid(userInfo.uid);
        user.setUsername(userInfo.username);
        user.setPhone(userInfo.phone);
        user.setGender(userInfo.gender);
        user.setBirthday(userInfo.birthday);
        user.setAvatar(userInfo.avatar);
        user.setToken("token_" + System.currentTimeMillis());
        
        return user;
    }
    
    
    private static Map<String, UserInfo> getUsers() {
        String json = SPUtils.getString(KEY_USERS);
        if (json.isEmpty()) {
            return new HashMap<>();
        }
        
        Type type = new TypeToken<Map<String, UserInfo>>() {}.getType();
        Map<String, UserInfo> users = gson.fromJson(json, type);
        return users != null ? users : new HashMap<>();
    }
    
    
    private static void saveUsers(Map<String, UserInfo> users) {
        String json = gson.toJson(users);
        SPUtils.putString(KEY_USERS, json);
    }
    
    
    public static boolean updateUserProfile(String uid, String gender, String birthday, String avatar) {
        Map<String, UserInfo> users = getUsers();
        
        // 查找用户
        for (UserInfo info : users.values()) {
            if (info.uid.equals(uid)) {
                // 更新扩展信息
                if (gender != null) {
                    info.gender = gender;
                }
                if (birthday != null) {
                    info.birthday = birthday;
                }
                if (avatar != null) {
                    info.avatar = avatar;
                }
                
                saveUsers(users);
                return true;
            }
        }
        
        return false;
    }
    
    
    public static User getUserInfo(String uid) {
        Map<String, UserInfo> users = getUsers();
        
        for (UserInfo info : users.values()) {
            if (info.uid.equals(uid)) {
                User user = new User();
                user.setUid(info.uid);
                user.setUsername(info.username);
                user.setPhone(info.phone);
                user.setGender(info.gender);
                user.setBirthday(info.birthday);
                user.setAvatar(info.avatar);
                return user;
            }
        }
        
        return null;
    }
    
    
    public static boolean resetPasswordByPhone(String phone, String newPassword) {
        Map<String, UserInfo> users = getUsers();
        
        for (UserInfo info : users.values()) {
            if (info.phone.equals(phone)) {
                info.password = newPassword;
                saveUsers(users);
                return true;
            }
        }
        
        return false;
    }
    
    
    public static boolean isPhoneRegistered(String phone) {
        Map<String, UserInfo> users = getUsers();
        
        for (UserInfo info : users.values()) {
            if (info.phone.equals(phone)) {
                return true;
            }
        }
        
        return false;
    }
    
    
    public static boolean verifyUserAndPhone(String username, String phone) {
        Map<String, UserInfo> users = getUsers();
        
        UserInfo userInfo = users.get(username);
        if (userInfo == null) {
            return false;
        }
        
        return userInfo.phone.equals(phone);
    }
    
    
    public static boolean resetPasswordByUsernameAndPhone(String username, String phone, String newPassword) {
        Map<String, UserInfo> users = getUsers();
        
        UserInfo userInfo = users.get(username);
        if (userInfo == null) {
            return false;
        }
        
        if (!userInfo.phone.equals(phone)) {
            return false;
        }
        
        userInfo.password = newPassword;
        saveUsers(users);
        return true;
    }
    
    
    public static User thirdPartyLogin(String platform, String thirdPartyId, String defaultUsername) {
        Map<String, UserInfo> users = getUsers();
        
        for (UserInfo info : users.values()) {
            if (platform.equals(info.thirdPartyPlatform) && thirdPartyId.equals(info.thirdPartyId)) {
                User user = new User();
                user.setUid(info.uid);
                user.setUsername(info.username);
                user.setPhone(info.phone != null ? info.phone : "");
                user.setGender(info.gender);
                user.setBirthday(info.birthday);
                user.setAvatar(info.avatar);
                user.setToken("token_" + System.currentTimeMillis());
                return user;
            }
        }
        
        String username = defaultUsername;
        int suffix = 1;
        while (users.containsKey(username)) {
            username = defaultUsername + suffix;
            suffix++;
        }
        
        UserInfo newUserInfo = new UserInfo();
        newUserInfo.uid = "UID_" + System.currentTimeMillis();
        newUserInfo.username = username;
        newUserInfo.phone = "";
        newUserInfo.password = "";
        newUserInfo.thirdPartyPlatform = platform;
        newUserInfo.thirdPartyId = thirdPartyId;
        
        users.put(username, newUserInfo);
        saveUsers(users);
        
        User user = new User();
        user.setUid(newUserInfo.uid);
        user.setUsername(newUserInfo.username);
        user.setPhone("");
        user.setToken("token_" + System.currentTimeMillis());
        
        return user;
    }
    
    
    private static class UserInfo {
        String uid;
        String username;
        String phone;
        String password;
        String gender;
        String birthday;
        String avatar;
        String thirdPartyPlatform;
        String thirdPartyId;
    }
}

